/*
 * Copyright 2009 Jinbo Lin. All rights reserved.
 * 
 * cn.edu.pku.dao.impl OfficeAutomation
 *
 * Created on 2009-12-21
 */
package cn.edu.pku.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import cn.edu.pku.dao.UserDao;
import cn.edu.pku.model.User;

/**
 * @author Jinbo Lin
 * 
 *  
 */
public class UserDaoHibernate extends HibernateDaoSupport implements UserDao {

	/* (non-Javadoc)
	 * @see cn.edu.pku.dao.UserDao#delete(int)
	 */
	@Override
	public void delete(int userId) {
		if (null != this.get(userId)) {
			this.getHibernateTemplate().delete(
				this.getHibernateTemplate().get(User.class, userId));
		}
	}

	/* (non-Javadoc)
	 * @see cn.edu.pku.dao.UserDao#delete(cn.edu.pku.model.User)
	 */
	@Override
	public void delete(User user) {
		if (null != this.get(user.getUserId())) {
			this.getHibernateTemplate().delete(user);
		}
	}

	/* (non-Javadoc)
	 * @see cn.edu.pku.dao.UserDao#findAll()
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<User> findAll() {
		String hql = "from User";
		return this.getHibernateTemplate().find(hql);
	}

	/* (non-Javadoc)
	 * @see cn.edu.pku.dao.UserDao#findUserIdByUserName(java.lang.String)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public int findUserIdByUserName(String userName) {
		String hql = "select user.userId from User user where user.userName=?";
		List<Integer> userIds = this.getHibernateTemplate().find(hql, userName);
		int userId = (null != userIds && 0 != userIds.size()) ? userIds.get(0).intValue() : 0;
		return userId;
	}

	/* (non-Javadoc)
	 * @see cn.edu.pku.dao.UserDao#get(int)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public User get(int userId) {
		String hql = "from User user where user.userId=?";
		List<User> users = this.getHibernateTemplate().find(
				hql, new Integer(userId));
		User user = (null != users && 0 != users.size()) ? users.get(0) : null;
		return user;
	}

	/* (non-Javadoc)
	 * @see cn.edu.pku.dao.UserDao#save(cn.edu.pku.model.User)
	 */
	@Override
	public Serializable save(User user) {
		if(0 == this.findUserIdByUserName(user.getUserName())) {
			this.getHibernateTemplate().save(user);
		} else {
			user = null;
		}
		return user;
	}

	/* (non-Javadoc)
	 * @see cn.edu.pku.dao.UserDao#update(cn.edu.pku.model.User)
	 */
	@Override
	public void update(User user) {
		if (null != this.get(user.getUserId())) {
//			this.getHibernateTemplate().saveOrUpdate(user);
			this.getHibernateTemplate().update(user);
		}
	}

}
